package com.app.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;

/**
 * 加密工具类
 */
public class EncryptUtils {

    /**
     * 加密
     */
    public static String encryptPassword(String pwd, String key) {
        try {
            Key _key = getDESSercretKey(key);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, _key);
            byte[] data = pwd.getBytes(StandardCharsets.UTF_8);
            byte[] result = cipher.doFinal(data);
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            throw new RuntimeException("密码处理异常");
        }
    }


    /**
     * 解密
     */
    public static String decryptPassowrd(String pwd, String key)
            throws Exception {
        Key aKey = getDESSercretKey(key);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, aKey);

        byte[] data = Base64.getDecoder().decode(pwd);
        byte[] result = cipher.doFinal(data);

        return new String(result, StandardCharsets.UTF_8);
    }

    /**
     * 获得DES加密秘钥
     *
     * @param key
     * @return
     * @throws UnsupportedEncodingException
     */
    public static SecretKey getDESSercretKey(String key) throws UnsupportedEncodingException {
        byte[] result = new byte[8];
        byte[] keys = null;
        keys = key.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < 8; i++) {
            if (i < keys.length) {
                result[i] = keys[i];
            } else {
                result[i] = 0x01;
            }
        }
        return new SecretKeySpec(result, "DES");
    }

    public static void main(String[] args) throws Exception {
        System.out.println(encryptPassword("111111", "1"));
        System.out.println(decryptPassowrd("UIlGv8sIOvY=", "1"));
    }
}
